<template>
  <el-dialog :model-value="dialogVisible" :title="titleObj[type]" width="600px" :before-close="handleClose"
    append-to-body>
    <el-form ref="formRef" :model="dataForm" label-width="130px" :rules="rules" :inline="false">
      <el-form-item label="类型名称：" prop="typeName">
        <el-input v-model="dataForm.typeName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="科目编码：" prop="typeCode">
        <el-input v-model="dataForm.typeCode" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="图标：" prop="iconUrl" class="icon-url">
        <el-input v-model="dataForm.iconUrl" placeholder="请输入" type="hidden" />
        <el-dropdown>
          <p class="drodown-box">
            <span class="el-dropdown-placeholder" v-if="dataForm.iconName == ''">
              请选择
            </span>
            <span class="el-dropdown-link" v-else>
              <FsSvgIcon :name="dataForm.iconName" style="font-size:20px" :style="{ color: dataForm.iconColor }" />
            </span>
            <span>
              <FsSvgIcon name="arrow-down" style="font-size:16px" />
            </span>
          </p>
          <template #dropdown>
            <el-dropdown-menu>
              <div class="icon-area">
                <ul>
                  <li v-for="(item, index) in 33" :key="index" class="icon-box" @click="selectIcon(index)">
                    <FsSvgIcon :name="'typeIcon-icon' + (index + 1)" style="font-size:20px"
                      :style="{ color: curIcon == index ? '#FF6667' : '#7F7F7F' }" />
                  </li>
                </ul>
              </div>

              <div class="icon-area color-area">
                <ul>
                  <li v-for="(item, index) in colorList" :key="index" class="icon-box"
                    @click="selectColor(item, index)">
                    <p :style="{ background: item }" :class="[curColorIndex == index ? 'active' : '']">
                      <img :src="selectIconUrl" alt="" v-if="curColorIndex == index">
                    </p>
                  </li>
                </ul>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-form-item>
      <el-form-item label="发票类型：" prop="invoiceType">
        <el-select v-model="dataForm.invoiceType" clearable style="width:100%" multiple @change="selectCanUseTaxType">
          <el-option v-for="item in invoiceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="typeStatus">
        <el-select v-model="dataForm.typeStatus" clearable style="width:100%">
          <el-option v-for="item in STATUS_LIST" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否可导入：" prop="allowImport">
        <el-select v-model="dataForm.allowImport" clearable style="width:100%">
          <el-option v-for="item in EXPORT_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submit()">保 存</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import api from "@/api/index";
import { ElMessage, ElMessageBox } from 'element-plus'
import { STATUS_LIST, EXPORT_OPTIONS } from '../Common/config'
import selectIconUrl from '@/icons/typeIcon/select.png'

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  type: {
    default: 'add',
    type: String

  },
  dataForm: {
    type: Object,
    default: () => { }
  },
  invoiceTypeOptions: {
    type: Array,
    default: () => []
  }


})

const loading = ref(false)

const colorList = ref(['#8C8C8C', '#FF6667', '#FFAA33', '#7EE518', '#30F2D2', '#1ABAFF', '#DAA6FF', '#FF99DD', '#8080FF', '#4A4A4A', '#D95758', '#B9741B', '#0CC161', '#02BFBF', '#0F82C1', '#AA7ACC', '#D962B1', '#6666CC'])

const curColorIndex = ref('-1')

const peopleList = ref([])

const titleObj = ref({
  'add': '新增',
  'edit': '编辑',
  'copy': '复制为',
})

var validateTypeCode = (rule, value, callback) => {
  const regex = /^\d{1,20}$/
  if (!regex.test(value)) {
    callback(new Error('请输入1-20位数字编码'));
  } else {
    callback();
  }
};

const rules = reactive({
  typeName: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  iconUrl: [
    {
      required: true,
      message: '请选择',
      trigger: 'blur'
    }
  ],
  typeStatus: [
    {
      required: true,
      message: '请选择',
      trigger: 'blur'
    }
  ],
  invoiceType: [
    {
      required: true,
      message: '请选择',
      trigger: 'blur'
    }
  ],
  typeCode: [
    {
      required: true,
      trigger: 'blur',
      validator: validateTypeCode
    }
  ],
  allowImport: [
    {
      required: true,
      message: '请选择',
      trigger: 'blur'
    }
  ],
})

const curIcon = ref(-1)

const formRef = ref(null)

const emit = defineEmits(['on-update', 'handleClose'])

const formInline = ref({
  hasConfig: "",
  orgCodeOrName: "",
});

const pageData = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const companyList = ref([])

onMounted(() => {

  // 回显图标
  if (props.type != 'add') {
    const { iconColor, iconName } = props.dataForm
    let colorIndex = colorList.value.findIndex(item => item == iconColor)
    curColorIndex.value = colorIndex
    let iconIndex = Number(iconName.substr(4)) - 1
    curIcon.value = iconIndex
    // searchCompany()
  }
});

const searchCompany = (query) => {
  if (query) {
    loading.value = true
    setTimeout(() => {
      loading.value = false
      companyList.value = getCompanyList()
    }, 200)
  } else {
    companyList.value = []
  }
}
// 选择可用税率类型
const selectCanUseTaxType = (val) => {
  let index = props.dataForm.invoiceType.findIndex(item => item == 'all')
  let values = props.invoiceTypeOptions.map(item => item.value)
  if (val.length == 1 && val[0] == 'all') {
    values.splice(index, 1)
    props.dataForm.invoiceType = values
  }
  else if (val.length < props.invoiceTypeOptions.length && val[val.length - 1] != 'all' && index > -1) {
    // 去掉全选
    props.dataForm.invoiceType.splice(index, 1)

  } else if (val[val.length - 1] == 'all') {
    values.splice(0, 1)
    props.dataForm.invoiceType = values
  }
}

// 获取公司
const getCompanyList = () => {
  return new Promise((resolve) => {
    const parms = {
      ...pageData.value,
      ...formInline.value,
    };
    api.dataMaintenance.getOrgTreeList(parms).then(res => {
      const { list, total } = res;
      companyList.value = list;
      resolve(list)
    })

  })


}
// 关闭
const handleClose = () => {
  formRef.value.resetFields()
  formRef.value.clearValidate()
  emit('handleClose')

}

const submit = () => {
  if (!formRef) return
  formRef.value.validate(valid => {
    if (valid) {
      const obj = {
        'add': 'feeTypeAdd',
        'edit': 'feeTypeEdit',
        'copy': 'feeTypeCopy',
      }

      const { id, typeName, iconUrl, typeStatus, iconName, iconColor } = props.dataForm
      const data = {
        ...props.dataForm
      }
      console.log(data)
      if (data.invoiceType.length > 0) {
        let index = data.invoiceType.findIndex(item => item == 'all')
        if (index > -1) data.invoiceType.splice(index, 1)
        data.invoiceType = data.invoiceType.join(",")
      }

      if (['add', 'copy'].includes(props.type)) data['id'] = null
      data['iconUrl'] = iconName + '_' + iconColor
      console.log(data)
      api.feeConfig[obj[props.type]](data).then(res => {
        handleClose()
        emit('on-update')
        ElMessage.success('操作成功')
      })


    } else {
      console.log('error submit!')
      return false
    }
  })
}

const selectIcon = (index) => {
  props.dataForm.iconName = 'typeIcon-icon' + (index + 1)
  props.dataForm.iconUrl = 'typeIcon-icon' + (index + 1)
  curIcon.value = index
}

const selectColor = (item, index) => {
  console.log(item)
  props.dataForm.iconColor = item
  curColorIndex.value = index
}


</script>
<style lang="scss">
.icon-url .el-tooltip__trigger,
.icon-url .el-dropdown {
  width: 100%;
}

::v-deep .el-popper {
  width: 400px !important;
}
</style>
<style lang="scss" scoped>
.el-dropdown-placeholder {
  color: #c0c4cc;
  font-size: 14px;
}

.drodown-box {
  display: flex;
  justify-content: space-between;
  width: 100%;
  border: 1px solid #dcdfe6;
  line-height: 32px;
  border-radius: 4px;
  padding: 0 10px;
  margin-bottom: 0;
  margin-top: 0;
}

.icon-box {
  padding: 5px 10px;
}

.icon-area {
  width: 450px;

  ul {
    margin: 0;
    padding: 0;
    padding-left: 5px;
    display: flex;
    flex-wrap: wrap;
    list-style-type: none;

    li {
      margin: 0;
      cursor: pointer;
    }
  }
}

.color-area {
  margin-top: 20px;

  ul {
    width: 380px;

    li {
      margin-right: 4px;

      p {
        width: 17px;
        height: 17px;
        border-radius: 50%;
        margin: 0;
        line-height: 17px;
        text-align: center;

        img {
          width: 10px;
          height: 8px;
        }

        &.active {
          position: relative;
          // top: -9px;
        }
      }
    }
  }
}
</style>
